import CNF from "../config";
import { createConnection, IConnection } from "mysql";
import { Card } from "../interfaces";
import { hashString } from "../libs/utils";
import { map, prop } from "ramda";

function query(con: IConnection, sql: string, data: any[]): Promise<Array<{}>> {
    return new Promise((resolve, reject) => {
        con.query(sql, data, (err, rows, fields) => err ? reject(err) : resolve(rows))
    })
}

async function store(card: Card) {
    let con = createConnection({
        database: CNF.DB_NAME,
        user: CNF.DB_USER_NAME,
        password: CNF.DB_PASSWORD
    })

    con.connect(err => {
        if (err) throw err
    })

    let pages = card.pages.map(t => {
        let json = JSON.stringify(t.elements)

        return {
            id: hashString(json),
            elements: json
        }
    })

    let pagesIds = map(prop('id'), pages)

    let existPages = await query(con, 'SELECT id, refs_count FROM xtb_template_pages WHERE id IN (?)', [pagesIds])
    let existIds = map(prop('id'), existPages)

    await Promise.all(
        pages.filter(p => !existIds.includes(p.id))
            .map(p => query(con, 'INSERT INTO xtb_template_pages(id, elements, refs_count) VALUES(?, ?, 1)', [p.id, p.elements]))
    )

    let existCard = await query(con, 'SELECT id FROM xtb_templates WHERE origin = ?', [card.origin])

    if (existCard.length > 0) {
        await query(con, 'UPDATE xtb_templates SET title= ?, pages= ? WHERE origin= ?', [card.title, pagesIds.join(), card.origin])
    } else {
        await query(con, 'INSERT INTO xtb_templates(title, pages, origin) VALUES(?, ?, ?)', [card.title, pagesIds.join(), card.origin])
    }

    con.end()
}

export default store